package com.feng.online_xdclass.service.Impl;

import com.feng.online_xdclass.exception.XDexception;
import com.feng.online_xdclass.mapper.*;
import com.feng.online_xdclass.model.entity.Episode;
import com.feng.online_xdclass.model.entity.PlayRecord;
import com.feng.online_xdclass.model.entity.Video;
import com.feng.online_xdclass.model.entity.VideoOrder;
import com.feng.online_xdclass.service.VideoOderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class VideoOderServiceImpl implements VideoOderService {
    @Autowired
    private VideoOrderMapper videoOrderMapper;
    @Autowired
    private UserMapper userMapper;
     @Autowired
     private VideoMapper videoMapper;
     @Autowired
     private EpisodeMapper episodeMapper;
     @Autowired
     private PlayRecordMapper playRecordMapper;
    /**
     * 下单操作
     * 未来版本：优惠券抵扣，风控用户检查，生成订单信息，生成支付信息
     * @param videoId
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public int save(Integer videoId, Integer userId) {
        //查询该用户是否已经购买了该video
        VideoOrder videoOrder = videoOrderMapper.findByUserIdAndVideoIdAndState(videoId, userId, 1);
        if(videoOrder!=null){
            //证明已经购买过
            return 0;
        }
        Video video = videoMapper.findById(videoId);
        VideoOrder newvideoOrder=new VideoOrder();
        newvideoOrder.setCreateTime(new Date());
        newvideoOrder.setUserId(userId);
        newvideoOrder.setState(1);
        newvideoOrder.setVideoTitle(video.getTitle());
        newvideoOrder.setOutTradeNo(UUID.randomUUID().toString());
        newvideoOrder.setTotalFee(video.getPrice());
        newvideoOrder.setVideoId(videoId);
        newvideoOrder.setVideoImg(video.getCoverImg());
        int rows=videoOrderMapper.saveOrder(newvideoOrder);
        //生成播放记录
        if(rows==1){
            Episode episode = episodeMapper.findfirst(videoId);
            if(episode==null){
                throw new XDexception(-1,"视频没有集信息,请运营人员检查！");
            }
            PlayRecord playRecord=new PlayRecord();
            playRecord.setCreateTime(new Date());
            playRecord.setCurrentNum(episode.getNum());
            playRecord.setEpisodeId(episode.getId());
            playRecord.setUserId(userId);
            playRecord.setVideoId(videoId);
            playRecordMapper.savePlayRecord(playRecord);


        }

        return rows;
    }
    @Override
    public List<VideoOrder> listOrderByUserId(Integer id) {
      return   videoOrderMapper.listOrderByUserId(id);
    }
}
